﻿
using Mate.Caching;
using Mate.Core;
using Mate.Core.Base;
using Mate.Db.Model.System;
using Mate.Db.SqlSugar;
using Mate.Dto.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mate.System.Service
{
    public class RolesService : DataService<roles>, IRolesService
    {
        private readonly ICacheManager cache;
        public RolesService(DataClient dataClient, ICacheManager cache) : base(dataClient)
        {
            this.cache = cache;
        }

        #region 获取列表
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="Key">关键字</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="recordCount">总条数</param>
        /// <returns></returns>
        public IList<roles> GetList(int pageIndex, int pageSize, string Key, ref int recordCount)
        {
            return dataClient.Queryable<roles>()
                 .WhereIF(!string.IsNullOrWhiteSpace(Key), x => x.role_name.Contains(Key))
                 .OrderBy(x => x.order_by, SqlSugar.OrderByType.Asc)
                 .ToPageList(pageIndex, pageSize, ref recordCount);
        }
        #endregion

        #region 获取所有角色
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public IList<roles> GetRoleAll()
        {
            return cache.Get<IList<roles>>(MateCacheKey.CacheRoleKey, 200, () =>
            {
                return dataClient.Queryable<roles>().OrderBy(x => x.order_by).ToList();
            });
        }
        #endregion


        #region 获取角色菜单
        /// <summary>
        /// 获取角色菜单
        /// </summary>
        /// <param name="rolesid"></param>
        /// <returns></returns>
        public IList<role_menu> GetRoleMenuList(int rolesid)
        {
            return dataClient.Queryable<role_menu>().Where(x => x.role_id == rolesid).ToList();
        }
        #endregion

        #region 根据角色获取菜单列表
        /// <summary>
        /// 根据角色获取菜单列表
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="isSuperAdmin"></param>
        /// <returns></returns>
        public IList<menu> GetMenuAll(int roleid, bool isSuperAdmin)
        {
            string key = string.Format(MateCacheKey.CacheRoleIdMenuCache, isSuperAdmin ? "All" : roleid.ToString());
            return cache.Get(key, 200, () =>
            {
                IList<menu> menuList;
                if (isSuperAdmin)
                {
                    menuList = dataClient.Queryable<menu>().Where(x => x.id > 0).OrderBy(x => x.order_by).ToList();
                }
                else
                {
                    menuList = dataClient.Queryable<role_menu, menu>((r, m) => new object[]{
                        JoinType.Left,r.menu_id == m.id
                         })
                        .Where((r, m) => r.role_id == roleid)
                        .Select<menu>("m.*")
                        .OrderBy("m.order_by")
                        .ToList();
                }
                return menuList;
            });
        }
        #endregion

        #region 根据角色获取导航列表
        /// <summary>
        /// 根据角色获取导航列表
        /// </summary>
        /// <param name="roleid">角色ID</param>
        /// <param name="isSuperAdmin">是否是超级管理员</param>
        /// <returns></returns>
        public IList<NavModel> GetNavAll(int roleid, bool isSuperAdmin)
        {
            if (roleid == 0) return null;
            var menuList = GetMenuAll(roleid, isSuperAdmin);

            if (menuList == null || menuList.Count == 0)
            {
                return null;
            }
            return menuList.Where(x => x.parent_id == 0 && x.menu_type == 1)
                .Select((x, i) =>
                {
                    return new NavModel()
                    {
                        title = x.menu_name,
                        icon = x.icons,
                        href = (string.IsNullOrWhiteSpace(x.controller_name) && string.IsNullOrWhiteSpace(x.action_name) 
                                    ? "" : string.Format("/{0}/{1}{2}", x.controller_name, x.action_name,x.url_parameter)),
                        spread = (i == 0) ? true : false,
                        children = menuList.Where(y => y.parent_id == x.id && x.menu_type == 1)
                         .Select(y =>
                         {
                             return new NavModel()
                             {
                                 title = y.menu_name,
                                 icon = y.icons,
                                 href = (string.IsNullOrWhiteSpace(y.controller_name) && string.IsNullOrWhiteSpace(y.action_name) 
                                            ? "" : string.Format("/{0}/{1}{2}", y.controller_name, y.action_name,y.url_parameter)),
                                 spread = false
                             };
                         }).ToList()
                    };
                }).ToList();
        }
        #endregion

        #region 权限设置
        /// <summary>
        /// 权限设置
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="menuids"></param>
        public BaseResult AuthorizationManager(int roleid, string menuids)
        {
            var result = new BaseResult();
            if (roleid > 0 && !string.IsNullOrWhiteSpace(menuids))
            {
                var role = Get(x => x.id == roleid);
                if (role == null)
                {
                    result.ResultCode = ResultCode.Fail;
                    result.Message = "参数错误";
                    return result;
                }

                string msg = string.Empty;
                string[] arr = menuids.Split(',');
                List<role_menu> list = new List<role_menu>();
                for (int i = 0; i < arr.Length; i++)
                {
                    list.Add(new role_menu() { role_id = roleid, menu_id = int.Parse(arr[i]) });
                }

                try
                {
                    dataClient.Ado.BeginTran();
                    if (dataClient.Queryable<role_menu>().Any(x => x.role_id == roleid))
                    {
                        dataClient.Deleteable<role_menu>(x => x.role_id == roleid).ExecuteCommand();
                    }
                    dataClient.Insertable(list).ExecuteCommand();
                    dataClient.Ado.CommitTran();
                    result.ResultCode = ResultCode.Success;
                    result.Message = "设置权限成功";
                }
                catch (Exception ex)
                {
                    dataClient.Ado.RollbackTran();
                    result.ResultCode = ResultCode.Fail;
                    result.Message = "设置权限失败!" + ex.Message;
                }
            }
            else
            {
                result.ResultCode = ResultCode.Fail;
                result.Message = "参数错误";
            }
            return result;
        }
        #endregion
    }
}
